package com.artieksi.util;

import com.google.common.base.Strings;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.context.ContextLoader;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * User: TTACANSEVER
 */
public class ArtiEksiUtil extends PropertyPlaceholderConfigurer {

	private static ConcurrentHashMap<String, String> PROPERTIES;

	@Override
	public void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
		super.processProperties(beanFactory, props);
		PROPERTIES = new ConcurrentHashMap<String, String>();
		for (Object key : props.keySet()) {
			String keyStr = key.toString();
			String valueStr = resolvePlaceholder(keyStr, props);
			PROPERTIES.put(keyStr, valueStr);
		}
	}
	
	public static String getMd5Password(String password) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        md.update(password.getBytes());
        byte[] mdbytes = md.digest();

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mdbytes.length; i++) {
            sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }

	public static String get(String property) {
		return PROPERTIES.get(property);
	}

    // before the Spring context initialized messageSource bean is null so take the parameter from the PROPERTIES map while Spring context is being initialized
	public static String getString(String property) {
		if (ContextLoader.getCurrentWebApplicationContext() != null)
			return ((ReloadableResourceBundleMessageSource) ContextLoader.getCurrentWebApplicationContext().getBean("messageSource")).getMessage(property, null, null).trim();
		else
			return get(property).trim();
	}

	public static Integer getInteger(String property) {
		if (ContextLoader.getCurrentWebApplicationContext() != null)
			return Integer.parseInt(((ReloadableResourceBundleMessageSource) ContextLoader.getCurrentWebApplicationContext().getBean("messageSource")).getMessage(property, null, null));
		else
			return Integer.parseInt(get(property));
	}

    public static Boolean getBoolean(String property) {
        return Boolean.parseBoolean(!Strings.isNullOrEmpty(get(property)) ? get(property) : "false");
    }

}
